package com.kedou.sdk.core;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kedou.sdk.params.bean.AccountInfo;
import com.kedou.sdk.params.bean.ConfigInfo;
import com.kedou.sdk.params.bean.RealNameInfo;
import com.kedou.sdk.params.bean.UserInfo;
import com.kedou.sdk.params.bean.VersionInfo;
import com.kedou.sdk.secret.Base64;
import com.kedou.sdk.utils.WL;
import com.kedou.sdk.utils.XmlUtils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/6/5 0005.
 */

public final class HttpEngineConduits {

    private static final String TAG = HttpEngineConduits.class.getSimpleName();
    private static final String FILE_NAME = "wansdksy";
    private static final int ACCOUNT_MAX_STORAGE_COUNT = 5;

    private final SharedPreferences sharedPreferences;
    private final SharedPreferences.Editor editor;
    private final List<AccountInfo> mUserAccountData;
    private final HashMap<String, Object> mCacheBuffer;

    boolean isLoggedIn = false;
    RealNameInfo realnameInfo;

    /**
     * 缓存是否直接打开悬浮窗内容界面，数据来源登录接口返回值，默认值false
     */
    private boolean openWindowContentView;

    HttpEngineConduits(Context context) {
        realnameInfo = new RealNameInfo();
        sharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        mUserAccountData = new ArrayList<AccountInfo>();
        mCacheBuffer = new HashMap<String, Object>();
    }

    public final boolean isOpenWindowContentView() {
        return openWindowContentView;
    }

    void setOpenWindowContentView(boolean openWindowContentView) {
        this.openWindowContentView = openWindowContentView;
    }

    public boolean isLoggedIn() {
        return isLoggedIn;
    }

    public RealNameInfo getRealnameInfo() {
        return realnameInfo;
    }

    void clearRealnameInfo(){
        realnameInfo = new RealNameInfo();
    }

    public void saveUserAccount(AccountInfo info) {
        List<AccountInfo> infos = readAllUserAccountInfo();

        if (!infos.contains(info)) {
            infos.add(0, info);
        } else {
            infos.remove(info);
            infos.add(0, info);
        }

        saveAllUserAccountInfo(infos);
    }

    public void saveAllUserAccountInfo(List<AccountInfo> accountInfos) {
        if (accountInfos != null && !accountInfos.isEmpty()) {
            final int accountSize = accountInfos.size();
            if (accountSize > ACCOUNT_MAX_STORAGE_COUNT) {
                for (int i = accountSize - 1; i > ACCOUNT_MAX_STORAGE_COUNT - 1; i--) {
                    accountInfos.remove(i);
                }
            }

            saveUserAccount();
        }
    }

    private void saveUserAccount() {
        String jsonString = new Gson().toJson(mUserAccountData);
        WL.d(TAG, "saveAllUserAccountInfo ---->jsonString: " + jsonString);
        saveUserAccount(jsonString);
    }

    private void saveUserAccount(String userAccount) {
        if (!TextUtils.isEmpty(userAccount)) {
            try {
                byte[] bytes = userAccount.getBytes("UTF-8");
                byte[] encodeBytes = Base64.encode(bytes, Base64.DEFAULT);
                String str = new String(encodeBytes, "UTF-8");

                mCacheBuffer.put("account", str);
                editor.putString("account", str);
                editor.commit();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    public AccountInfo findUserAccountByUsername(String username) {
        List<AccountInfo> infos = readAllUserAccountInfo();
        if (infos != null) {
            for (AccountInfo info : infos) {
                if (info != null && username.equals(info.getUsername())) {
                    return info;
                }
            }
        }
        return null;
    }

    public AccountInfo findUserAccountByUserId(String userId) {
        List<AccountInfo> infos = readAllUserAccountInfo();
        if (infos != null) {
            for (AccountInfo info : infos) {
                if (info != null && userId.equals(info.getUserId())) {
                    return info;
                }
            }
        }
        return null;
    }

    public List<AccountInfo> readAllUserAccountInfo() {
        if (mUserAccountData.isEmpty()) {
            String jsonString = readUserAccount();
            WL.d(TAG, "readAllUserAccountInfo ---->jsonString: " + jsonString);
            Type listType = new TypeToken<ArrayList<AccountInfo>>() {}.getType();
            List<AccountInfo> temps = new Gson().fromJson(jsonString, listType);
            if (temps != null) {
                mUserAccountData.addAll(temps);
            }
        }
        return mUserAccountData;
    }

    private String readUserAccount() {
        String accountInfo;
        if (mCacheBuffer.containsKey("account")) {
            accountInfo = (String) mCacheBuffer.get("account");
        } else {
            accountInfo = sharedPreferences.getString("account", "");
            mCacheBuffer.put("account", accountInfo);
        }

        if (!TextUtils.isEmpty(accountInfo)) {
            try {
                byte[] bytes = Base64.decode(accountInfo, Base64.DEFAULT);
                return new String(bytes, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public void deleteUserAccount(AccountInfo accountInfo) {
        if (mUserAccountData.contains(accountInfo)) {
            mUserAccountData.remove(accountInfo);
        }
        saveUserAccount();
    }

    public void saveCurrentLoginUserUID(String uid) {
        mCacheBuffer.put("uid", uid);
        editor.putString("uid", uid);
        editor.commit();
    }

    public String readCurrentLoginUserUID() {
        String uid = (String) mCacheBuffer.get("uid");
        if (TextUtils.isEmpty(uid)) {
            uid = sharedPreferences.getString("uid", "");
            mCacheBuffer.put("uid", uid);
        }
        return uid;
    }


    public void saveCurrentOaid(String oaid){
        mCacheBuffer.put("oaid", oaid);
        editor.putString("oaid", oaid);
        editor.commit();
    }

    public String readCurrentOaid(){
        String oaid = (String) mCacheBuffer.get("oaid");
        if (TextUtils.isEmpty(oaid)) {
            oaid = sharedPreferences.getString("oaid", "");
            mCacheBuffer.put("oaid", oaid);
        }
        return oaid;
    }
    public void saveDeviceCode(String oaid){
        mCacheBuffer.put("device_code", oaid);
        editor.putString("device_code", oaid);
        editor.commit();
    }

    public String readDeviceCode(){
        String oaid = (String) mCacheBuffer.get("device_code");
        if (TextUtils.isEmpty(oaid)) {
            oaid = sharedPreferences.getString("device_code", "");
            mCacheBuffer.put("device_code", oaid);
        }
        return oaid;
    }


    public String readIdcardMsg() {
        String uid = (String) mCacheBuffer.get("idcardmsg");
        return uid;
    }

    public void saveIdcardMsg(String ticket) {
        mCacheBuffer.put("idcardmsg", TextUtils.isEmpty(ticket)?"":ticket);
    }

    public String readCurrentLoginUserTicket() {
        String uid = (String) mCacheBuffer.get("ticket");
        if (TextUtils.isEmpty(uid)) {
            uid = sharedPreferences.getString("ticket", "");
            mCacheBuffer.put("ticket", uid);
        }
        return uid;
    }

    public void saveCurrentLoginUserTickit(String ticket) {
        mCacheBuffer.put("ticket", ticket);
        editor.putString("ticket", ticket);
        editor.commit();
    }

    public void saveCurrentOrder(String ticket) {
        mCacheBuffer.put("defaultOrder", ticket);
        editor.putString("defaultOrder", ticket);
        editor.commit();
    }
    public String readCurrentOrder() {
        String uid = (String) mCacheBuffer.get("defaultOrder");
        if (TextUtils.isEmpty(uid)) {
            uid = sharedPreferences.getString("defaultOrder", "");
            mCacheBuffer.put("defaultOrder", uid);
        }
        return uid;
    }

    public void saveDefaultSmallAccount(String ticket) {
        mCacheBuffer.put("defaultAccount", ticket);
        editor.putString("defaultAccount", ticket);
        editor.commit();
    }
    public String readDefaultSmallAccount() {
        String uid = (String) mCacheBuffer.get("defaultAccount");
        if (TextUtils.isEmpty(uid)) {
            uid = sharedPreferences.getString("defaultAccount", "");
            mCacheBuffer.put("defaultAccount", uid);
        }
        return uid;
    }

    public void saveLastLoginSmallAccount(String ticket) {
        mCacheBuffer.put("lastLoginAccount", ticket);
        editor.putString("lastLoginAccount", ticket);
        editor.commit();
    }
    public String readLastLoginSmallAccount() {
        String uid = (String) mCacheBuffer.get("lastLoginAccount");
        if (TextUtils.isEmpty(uid)) {
            uid = sharedPreferences.getString("lastLoginAccount", "");
            mCacheBuffer.put("lastLoginAccount", uid);
        }
        return uid;
    }


    public String readCurrentLoginUserRefrshTicket() {
        String uid = (String) mCacheBuffer.get("refresh_ticket");
        if (TextUtils.isEmpty(uid)) {
            uid = sharedPreferences.getString("refresh_ticket", "");
            mCacheBuffer.put("refresh_ticket", uid);
        }
        return uid;
    }

    public void saveCurrentLoginUserRefreshTickit(String ticket) {
        mCacheBuffer.put("refresh_ticket", ticket);
        editor.putString("refresh_ticket", ticket);
        editor.commit();
    }

    public void saveGameId(String gameId) {
        mCacheBuffer.put("gameId", gameId);
        editor.putString("gameId", gameId);
        editor.commit();
    }

    public String readGameId() {
        String gameId = (String) mCacheBuffer.get("gameId");
        if (TextUtils.isEmpty(gameId)) {
            gameId = sharedPreferences.getString("gameId", "");
            mCacheBuffer.put("gameId", gameId);
        }
        return gameId;
    }

    public boolean isForeverForbidAlertPermission() {
        if (mCacheBuffer.containsKey("AlertPermission")) {
            return (boolean) mCacheBuffer.get("AlertPermission");
        }
        return sharedPreferences.getBoolean("AlertPermission", false);
    }

    public void setForeverForbidAlertPermission(boolean isForever) {
        mCacheBuffer.put("AlertPermission", isForever);
        editor.putBoolean("AlertPermission", isForever);
        editor.commit();
    }

    public void setPlatformConfigInfo(ConfigInfo info){

        mCacheBuffer.put("configInfo", info);
        saveDeviceCode(info.getDevice_code());
    }

    public UserInfo getBoxuser(){
        return (UserInfo) mCacheBuffer.get("boxUser");
    }

    public void saveBoxUser(UserInfo info){

        mCacheBuffer.put("boxUser", info);
    }

    public ConfigInfo getPlatformConfigInfo(){
        return (ConfigInfo) mCacheBuffer.get("configInfo");
    }

    public void saveLastLoginPhoneNumber(String cellphone) {
        mCacheBuffer.put("cellphone", cellphone);
        editor.putString("cellphone", cellphone);
        editor.commit();
    }

    public String readLastLoginPhoneNumber() {
        String cellphone = (String) mCacheBuffer.get("cellphone");
        if (TextUtils.isEmpty(cellphone)) {
            cellphone = sharedPreferences.getString("cellphone", "");
            mCacheBuffer.put("cellphone", cellphone);
        }
        return cellphone;
    }

    public void writeLastLoginType(int loginType) {
        Log.e("loginType","writeLastLoginType "+loginType);
        mCacheBuffer.put("loginType", loginType);
        editor.putInt("loginType", loginType);
        editor.commit();
    }

    public int readLastLoginType() {
        Object loginType = mCacheBuffer.get("loginType");
        Log.e("loginType","readLastLoginType out."+loginType);
        if (loginType == null) {
            loginType = sharedPreferences.getInt("loginType", XmlUtils.isPutInChannel()&&"3.1.12".equals(XmlUtils.getSdkVersionName())?0:1);
            mCacheBuffer.put("loginType", loginType);
            Log.e("loginType","readLastLoginType."+loginType);
        }
        return loginType instanceof Integer ? (Integer) loginType : XmlUtils.isPutInChannel()&&"3.1.12".equals(XmlUtils.getSdkVersionName())?0:1;
    }

    public void writeAutoLogin(boolean auto){
        mCacheBuffer.put("autoLogin", auto);
        editor.putBoolean("autoLogin", auto);
        editor.commit();
    }

    public void writeAgreePrivate(){

        editor.putBoolean("agreePrivate", true);
        editor.commit();
    }

    public boolean readAgreePrivate() {
        return sharedPreferences.getBoolean("agreePrivate", false);
    }

    public void writeLoginAgreePrivate(){

        editor.putBoolean("agreeLoginPrivate", true);
        editor.commit();
    }

    public boolean readLoginAgreePrivate() {
        return sharedPreferences.getBoolean("agreeLoginPrivate", false);
    }


    public boolean readAutoLogin() {
        Object loginType = mCacheBuffer.get("autoLogin");
        if (loginType == null) {
            loginType = sharedPreferences.getBoolean("autoLogin", true);
            mCacheBuffer.put("autoLogin", loginType);
        }
        return loginType instanceof Boolean ? (Boolean) loginType : true;
    }

    public void writeVersionDownloadId(long downloadId){
        mCacheBuffer.put("downloadId", downloadId);
        editor.putLong("downloadId", downloadId);
        editor.commit();
    }

    public long readVersionDownloadId(){
        Long downloadId = (Long) mCacheBuffer.get("downloadId");
        if (downloadId == null) {
            downloadId = sharedPreferences.getLong("downloadId", 0);
            mCacheBuffer.put("downloadId", downloadId);
        }
        return downloadId;
    }

    public void cacheVersionInfo(VersionInfo versionInfo){
        if(!mCacheBuffer.containsValue(versionInfo)){
            mCacheBuffer.put("versionInfo", versionInfo);
        }
    }

    public VersionInfo readVersionInfo(){
        Object object = mCacheBuffer.get("versionInfo");
        if(object instanceof VersionInfo){
            return (VersionInfo) object;
        }

        return new VersionInfo();
    }

    public void saveLastPushTime(String lastTime) {
        mCacheBuffer.put("last_push_time", lastTime);
        editor.putString("last_push_time", lastTime);
        editor.commit();
    }

    public String readLastPushTime() {
        String cellphone = (String) mCacheBuffer.get("last_push_time");
        if (TextUtils.isEmpty(cellphone)) {
            cellphone = sharedPreferences.getString("last_push_time", "0");
            mCacheBuffer.put("last_push_time", cellphone);
        }
        return cellphone;
    }

    public void saveReportRegist(int report){
        editor.putInt("report_regist", report);
        editor.commit();
    }

    public void saveReportActive(int report){
        editor.putInt("report_active", report);
        editor.commit();
    }

    public void saveClosePhoneLogin(int close){
        mCacheBuffer.put("close_phone_login", close);
        editor.putInt("close_phone_login", close);
        editor.commit();
    }

    public boolean readClosePhoneLogin(){
        if(mCacheBuffer.containsKey("close_phone_login")){
            return (int)mCacheBuffer.get("close_phone_login")==1;
        }else {
            return sharedPreferences.getInt("close_phone_login",0)==1;
        }
    }

    public void saveFloatWindowType(String type){
        if(TextUtils.isEmpty(type))type="";
        mCacheBuffer.put("float_window_type", type);
        editor.putString("float_window_type", type);
        editor.commit();
    }

    public String readFloatWindowType(){
        String type;
        if(mCacheBuffer.containsKey("float_window_type")){
            type = (String)mCacheBuffer.get("float_window_type");
        }else {
            type =sharedPreferences.getString("float_window_type","");
        }

        return type;
    }

    public void saveIDcardUiType(int type){
        mCacheBuffer.put("idcard_ui_type", type);
        editor.putInt("idcard_ui_type", type);
        editor.commit();
    }

    public int readIDcardUiType(){
        if(mCacheBuffer.containsKey("idcard_ui_type")){
            return (int)mCacheBuffer.get("idcard_ui_type");
        }else {
            return sharedPreferences.getInt("idcard_ui_type",0);
        }
    }

    public void saveNeedPull(int need){
        mCacheBuffer.put("need_pull_activity", need);
        editor.putInt("need_pull_activity", need);
        editor.commit();
    }

    public boolean readNeedPull(){
        if(mCacheBuffer.containsKey("need_pull_activity")){
            return (int)mCacheBuffer.get("need_pull_activity")==1;
        }else {
            return sharedPreferences.getInt("need_pull_activity",1)==1;
        }
    }

}
